<?php

namespace app\components;

use yii;
use yii\filters\AccessControl;

class WebAuthController extends WebController {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    ['actions' => ['login'], 'allow' => TRUE, 'roles' => ['?']],
                    ['actions' => ['error'], 'allow' => TRUE, 'roles' => ['@']],
                    ['allow' => TRUE, 'roles' => ['@']],
                ],
                'denyCallback' => function ($rule, $action) {
                    if ($action->id !== 'login' && !empty(Yii::$app->user->loginUrl)) {
                        Yii::$app->user->loginUrl['ref'] = Yii::$app->request->url;
                    }
                    Yii::$app->user->loginRequired();
                }
            ]
        ];
    }

    public function beforeAction($action) {
        if (!parent::beforeAction($action)) {
            return FALSE;
        }
        if (!Yii::$app->user->isGuest && $this->user->type <= 0 && !in_array($action->id, ['identity', 'logout', 'verify'])) {
            $this->redirect(['user/identity']);
            return FALSE;
        }
        if (!Yii::$app->user->isGuest && $this->user->getIsDisabled()) {
            Yii::$app->user->logout();
            Yii::$app->getResponse()->redirect(['/auth/login']);
            return FALSE;
        }
        return TRUE;
    }

    public function deleteById($id) {
        $model = $this->findModel($id);

        if ($model->delete() === FALSE) {
            return $this->error($model->getError());
        }
        return $this->success();
    }

    public function actionLogout() {
        Yii::$app->user->logout();
        return Yii::$app->getResponse()->redirect(['/auth/login']);
    }
}